package com.example.pages;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import com.example.data.SorterListOf;
import com.example.data.User;
import com.google.common.collect.Lists;

public class UserManagementPage extends InternalPage {

	@FindBy(id= "username")
	public WebElement usernameField;
	
	@FindBy(name= "email")
	public WebElement emailField;
	
	@FindBy(id= "password")
	public WebElement passwordField;
	
	@FindBy(id= "password2")
	public WebElement passwordConfirmationField;
	
	@FindBy(name= "submit")
	public WebElement submitButton;
	
	@FindBy(xpath = "html/body/div[1]/div/div/section/div[2]/table/tbody/tr[2]/td[2]/a")
	public WebElement secondUserLink;
	
	@FindBy(css = "h3 + table > tbody> tr")
	public List<WebElement> usersRows;

	public UserManagementPage createUser(User user) {
		usernameField.clear();
		usernameField.sendKeys(user.name);
		emailField.clear();
		emailField.sendKeys(user.email);
		passwordField.clear();
		passwordField.sendKeys(user.password);
		passwordConfirmationField.clear();
		passwordConfirmationField.sendKeys(user.password);
		submitButton.click();
		return MyPageFactory.getPage(driver, UserManagementPage.class);
	}
	
	public UserManagementPage deleteUser(User user) {
		
		for (WebElement row: usersRows){
			if (user.equals(convertRowToUser(row))){
				row.findElement(By.xpath("./td[6]/a")).click();
				driver.switchTo().alert().accept();
				break;
			}
		}
		return MyPageFactory.getPage(driver, UserManagementPage.class);
	}

	public SorterListOf<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row: usersRows){
			users.add(convertRowToUser(row));
		}
		return new SorterListOf<User>(users);
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User()
			.withName(cells.get(1).getText())
			.withEmail(cells.get(2).getText())
			.withRole(cells.get(3).getText());
	}
	
}
